package com.qxzn.app.api.util;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;

import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.Constant;

import java.io.File;

public class DownloadBroadcast extends BroadcastReceiver {

    private File downLoadFile;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            AppUtil.showLog("下载完成，action:" + action);
            if (downLoadFile != null) {
                Intent intent1 = new Intent(Intent.ACTION_VIEW);
                intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                    intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri uri1 = FileProvider.getUriForFile(context, Constant.authority, downLoadFile);
                    intent1.setDataAndType(uri1, "application/vnd.android.package-archive");
                } else {
                    intent1.setDataAndType(Uri.fromFile(downLoadFile), "application/vnd.android.package-archive");
                }
                AppUtil.showLog("mFile:" + downLoadFile);
                try {
                    context.startActivity(intent1);
                } catch (Exception e) {
                    AppUtil.showLog("安装启动异常:" + e);
                    e.printStackTrace();
                }
            }
        }
    }

    public File getDownLoadFile() {
        return downLoadFile;
    }

    public void setDownLoadFile(File downLoadFile) {
        this.downLoadFile = downLoadFile;
    }
}